<?php

namespace app\controller;

use app\BaseController;
use app\model\File;
use think\helper\Str;
use think\response\Json;

class Upload extends BaseController
{
    public function image(): Json
    {
        return $this->handle(function () {
            $file = request()->file('image');
            if (empty($file)) throw new \Exception('上传文件为空', 7097);
            return $this->saveImg($file, 'images');
        });
    }

    public function imageLst(): Json
    {
        return $this->handle(function () {
            return $this->app->make(File::class)->pageData();
        });
    }

    public function delImage(): Json
    {
        return $this->handle(function (){
            return $this->app->make(File::class)->delData();
        });
    }

    protected function saveImg($file, $dirName): array
    {
        $dir = "./upload/$dirName/" . date('Ymd/');
        if (!file_exists($dir)) {
            mkdir($dir, 0777, true);
        }
        $lastName = $file->getOriginalName();
        $fileName = md5(time() . Str::random(8)) . '.' . $file->extension();
        $size = $file->getSize();
        $ext = $file->extension();
        $file->move($dir, $fileName);
        $path = $this->request->domain() . "/upload/$dirName/" . date('Ymd/') . $fileName;
        //存储文件信息
        $this->app->make(\app\model\File::class)->save([
            'name' => $lastName,
            'url' => $path,
            'size' => $size,
            'ext' => $ext,
            'dir' => $dir . $fileName
        ]);
        return [
            'name' => $lastName,
            'url' => $path,
            'size' => $size,
            'ext' => $ext
        ];
    }
}
